import React, {useEffect, useState, useRef} from "react";
import {Image, StyleSheet, View, Text, ImageBackground, TouchableOpacity, ScrollView} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

import emptyIcon from "@/assets/images/me/empty_icon.png"
import { scaleSize} from "@/utils/screenSize"


const TaskScreen = ({ height, List, setTaskList }) => {
    const [length, setLength] = useState(2);
    const [data, setData] = useState(List);
    const [loading, setLoading] = useState(false);
    const scrollViewRef = useRef(null);
    const [scrollPosition, setScrollPosition] = useState(0);

    useEffect(() => {
        return () => {
            AsyncStorage.setItem('meTaskScrollPosition', JSON.stringify(scrollPosition));
        };
    }, [scrollPosition]);

    // 在组件挂载时恢复滚动位置
    useEffect(() => {
        const restorePosition = async () => {
            const savedPosition = await AsyncStorage.getItem('meTaskScrollPosition');
            if (savedPosition) {
                const position = JSON.parse(savedPosition);
                console.log('position', position)
                console.log('scrollViewRef', scrollViewRef);
                setTimeout(() => {
                    scrollViewRef.current?.scrollTo({ y: position, animated: true });
                }, 0)
            }
        };

        setTimeout(() => {
            restorePosition();
        }, 100)
    }, []);

    // 模拟加载更多数据的函数
    const loadMoreData = () => {
        if (loading) return; // 防止重复加载

        setLoading(true);
        setTimeout(() => {
            setData([...data, ...List]);
            setTaskList([...data, ...List]);
            setLoading(false);
        }, 100); // 模拟网络请求的延迟
    };



    // 检测是否到达底部
    const handleScroll = ({ nativeEvent }) => {
        const isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => {
            return layoutMeasurement.height + contentOffset.y >= contentSize.height - 20;
        };

        if (isCloseToBottom(nativeEvent) && data.length < 100) {
            loadMoreData();
        }

        const yOffset = nativeEvent.contentOffset.y;
        console.log('yOffset', yOffset);
        setScrollPosition(yOffset);
    };


    const NoMoreData = () => {
        return (
            <View style={styles.NoMoreDatacontainer}>
                <View style={styles.NoMoreDataline} />
                <Text style={styles.NoMoreDatatext}>没有更多了</Text>
                <View style={styles.NoMoreDataline} />
            </View>
        );
    };


    console.log('height', height);


    return (
        <View style={{ flex: 1 }}>
            {
                length == 0 && (
                    <View style={styles.toolWrap}>
                        <ImageBackground source={emptyIcon} style={{ width: "100%", height: "100%" }}>
                            <View style={styles.empty_wrap}>
                                <Text style={ styles.empty_text }>空空如也~</Text>
                            </View>
                        </ImageBackground>
                    </View>
                )
            }

            {
                length > 0 && (
                    <ScrollView
                        style={{ flex: 1 }}
                        scrollEventThrottle={16}
                        onScroll={handleScroll}
                        ref={scrollViewRef}
                    >
                        {
                            data.map((item: any, index: number) => {
                                return (
                                    <View style={styles.taskWarp}>
                                        <ImageBackground style={ styles.avator }>
                                            <View></View>
                                        </ImageBackground>
                                        <View style={styles.taskTitleWrap}>
                                            <Text style={styles.taskTitle}>{ item.name }</Text>
                                        </View>
                                        <TouchableOpacity>
                                            <View style={styles.goTaskBtn}>
                                                <Text style={styles.goTaskBtnText}>去完成</Text>
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                )
                            })
                        }
                        {
                            !loading && data.length < 100 && (
                                <View style={{ marginTop: 12, paddingBottom: 50 }}>
                                    <Text style={ styles.loadingMore }>加载更多...</Text>
                                </View>
                            )
                        }
                        {
                            loading && data.length < 100 && (
                                <View style={{ marginTop: 12, paddingBottom: 50 }}>
                                    <Text style={ styles.loadingMore }>正在加载...</Text>
                                </View>
                            )
                        }
                        {
                            !loading &&data.length >= 100 && (
                                <NoMoreData/>
                            )
                        }
                    </ScrollView>
                )
            }
        </View>
    );
}

export default React.memo(TaskScreen);

const styles = StyleSheet.create({
    toolWrap: {
        width: scaleSize(220),
        height: scaleSize(220),
        margin: "auto",
        // backgroundColor: "red",
        marginTop: 57,
    },
    empty_wrap: {
        marginTop: 185,
    },
    empty_text: {
        fontSize: 14,
        textAlign: "center",
        color: "#9C9EAC",
        paddingLeft: 10,
    },
    taskWarp: {
        borderWidth: 1,
        borderStyle: "solid",
        borderColor: "#F7F8F9",
        flexDirection: "row",
        alignItems: "center",
        width: scaleSize(349),
        height: 58,
        // backgroundColor: "red",
        marginTop: 12,
        marginLeft: 12,
    },
    avator: {
        width: scaleSize(38),
        height:scaleSize(38),
        borderRadius: 50,
        backgroundColor: "blue",
        marginLeft: scaleSize(12),
    },
    taskTitleWrap: {
        marginLeft: 12,
        width: scaleSize(180),
    },
    taskTitle: {
        fontSize: 14,
        color: '#2A2B30',
    },
    goTaskBtn: {
        width: scaleSize(56),
        height: scaleSize(26),
        // backgroundColor: "red",
        borderRadius: 13,
        borderWidth: 1,
        borderStyle: "solid",
        borderColor: "#EC6138",
        marginLeft: 42,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center"
    },
    goTaskBtnText: {
        color: "#EC6138",
        fontSize: 12,
    },
    loadingMore: {
        textAlign: "center",
        color: "rgb(96, 98, 102)",
    },
    NoMoreDatacontainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginVertical: 20,
        paddingBottom: 30,
    },
    NoMoreDataline: {
        width: 80,
        height: 0.5,
        backgroundColor: '#ccc',
    },
    NoMoreDatatext: {
        marginHorizontal: 10,
        color: '#888',
        fontSize: 14,
    },
});
